package com.hb.commons;

import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

/**
 * 基于 [String, String]的redis操作工具类
 *
 * @author zhaojk
 */
public class StringRedisService extends AbstractRedisService<String, String> {

    public StringRedisService(StringRedisTemplate stringRedisTemplate) {
        super(stringRedisTemplate);
    }

    /**
     * 设置redis键值对
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value);
        setDataBase(0);
    }

    /**
     * 设置redis键值对
     *
     * @param key
     * @param value
     * @param timeout 过期时间(毫秒)
     */
    public void set(String key, String value, long timeout) {
        set(key, value, timeout, TimeUnit.MILLISECONDS);
    }

    /**
     * 设置redis键值对
     *
     * @param key
     * @param value
     * @param timeout 过期时间
     * @param unit    过期时间单位
     */
    public void set(String key, String value, long timeout, TimeUnit unit) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value, timeout, unit);
        setDataBase(0);
    }

    /**
     * 设置redis键值对
     *
     * @param key 指定键
     *
     * @return
     */
    public String get(String key) {
        return get(key, null);
    }

    /**
     * 设置redis键值对
     *
     * @param key          指定键
     * @param defaultValue 默认值
     *
     * @return
     */
    public String get(String key, String defaultValue) {
        if (StrUtil.isEmpty(key)) {
            return defaultValue;
        }
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String value = valueOperations.get(key);
        if (StrUtil.isEmpty(value)) {
            return defaultValue;
        }
        return value;
    }
}
